API Call in Service Using HttpClient | Get & Display Data

API Call Using Service in Angular

In previous parts, API and Service were explained.

API is used to share data between backend and frontend.

Service is an Angular feature used to store common data, logic, and API calls.

API is not an Angular feature.

Service is an Angular feature.


Why API Call is Done Inside Service

API calls are kept inside services so they can be reused.

Common API calls, common data, and common logic are written in services.

Components only use the service to get data.


API Operations Used

With APIs, mainly four operations are used:

  1. Get data from backend
  2. Store data in backend
  3. Update data in backend
  4. Delete data from backend

Free APIs mostly allow only get data operations.

So here, a get API is used to display data.


Dummy API Used

A dummy products API is used from a dummy JSON website.

This API provides product data that can be displayed in the Angular app.


Creating Service

Service is created using Angular CLI.

Service is placed inside a services folder.

This keeps all services organized.


Service Code (API Call)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class ProductsService {

apiUrl = 'https://dummyjson.com/products';

constructor(private http: HttpClient) {}

getProducts() {
return this.http.get(this.apiUrl);
}
}

HttpClient is required to call APIs.

HttpClient must be imported.

get() method is used because data is fetched from API.


Using Service in Component

Service is injected inside the component using constructor.

constructor(private productsService: ProductsService) {}

API is called inside ngOnInit.


ngOnInit() {
this.productsService.getProducts().subscribe((data: any) => {
console.log(data);
});
}

subscribe() is used because API data comes asynchronously.


Storing API Data

A signal is used to store product data.

productData = signal<any>([]);

API response data is set into the signal.

this.productData.set(data.products);


Displaying Data in HTML

<h1>Product List</h1>

<ul class="product-ul">
@for (product of productData(); track product.id) {
<li>
{{ product.title }} <br>
Price: {{ product.price }} <br>
Category: {{ product.category }}
</li>
}
</ul>

Double curly braces are used for interpolation.

@for is used to loop over products.


Styling (CSS)

.product-ul li {
border-bottom: 1px solid #ccc;
padding: 5px;
}

This helps separate each product visually.